package com.arkisv.common.conf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.arkisv.common.util.PageUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonInputMessage;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * RequestBody拦截
 */
@Order(1)
@ControllerAdvice
public class ApplicationJsonRequestBodyAdvice extends RequestBodyAdviceAdapter {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return (converterType.isAssignableFrom(MappingJackson2HttpMessageConverter.class));
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        if (converterType.isAssignableFrom(MappingJackson2HttpMessageConverter.class)) {
            String body = IOUtils.toString(inputMessage.getBody());
            // 分页拦截
            pageIntercept(body);
            return new MappingJacksonInputMessage(IOUtils.toInputStream(body), inputMessage.getHeaders());
        }
        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }

    private void pageIntercept(String body) {
        if (!body.startsWith("[")) {
            JSONObject jsonObject = null;
            try {
                jsonObject = JSON.parseObject(body);
            } catch (Exception e) {
            }

            // 页码
            Integer pageNum = jsonObject.getInteger("pageNum");
            if (pageNum == null) {
                return;
            }
            // 每页显示条数
            Integer pageSize = jsonObject.getInteger("pageSize");
            pageSize = pageSize == null ? PageUtil.DEFAULT_PAGE_SIZE : pageSize;
            pageSize = pageSize > PageUtil.MAX_PAGE_SIZE ? PageUtil.MAX_PAGE_SIZE : pageSize;
            PageHelper.startPage(pageNum, pageSize);
        }

    }

}

